package com.zhj.juc.demo12;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @PackageName:com.zhj.juc.demo12
 * @ClassName:Test2Volatile
 * @auter: 朱慧杰
 * @date:2020/7/24 0024 22:38
 **/
public class Test2Volatile {

    // volatile 不保证原子性
    private volatile static AtomicInteger num = new AtomicInteger();  // 原子类的包装类

    public static void add(){
        // 在内存中 1.获得值 2.加一 3.改回去
        num.getAndIncrement();  // +1 操作   CAS
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }

        while (Thread.activeCount()>2) {
            Thread.yield();
        }

        System.out.println(Thread.currentThread().getName() + " num = " + num);
    }

}
